<template>
  <div class="privateSecretManagement">
    <MetaPageTable
      ref="privateSecretManagementTable"
      class="privateSecretManagement_table"
      table-title="认证列表"
      :is-auto-req="true"
      :req-url="reqUrl"
      :req-data="searchDataForTable"
      req-method="post"
      :display-item="displayItem"
      :btn-group="btnGroup"
      :line-btn-group="lineBtnGroup"
      @btnClick="tableBtnClick"
      @lineBtnClick="tableInlineBtnClick"
    />
    <el-dialog
      v-if="privateSecretDialogFlag"
      :title="itemEditData.id && itemEditData.id !== '' ? '编辑认证' : '新建认证'"
      :visible.sync="privateSecretDialogFlag"
      width="60%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="tPrivateSecretEdit_form" :model="itemEditData" label-width="150px" :rules="editRules">
        <el-form-item label="客户名称" prop="cid">
          <el-select
            v-model="itemEditData.cid"
            placeholder="请选择客户"
            clearable
            filterable
            style="width: 80%"
            @change="showClientName"
            :disabled="itemEditData.id && itemEditData.id !== '' ? true : false">
            <el-option
              v-for="item in apiCustomerInfoList"
              :key="item.id"
              :label="item.clientName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机器标识" prop="hostKey">
          <el-input v-model="itemEditData.hostKey" placeholder="请输入机器标识"></el-input>
        </el-form-item>
        <el-form-item label="生效时间" prop="startTime">
          <el-date-picker
            v-model="itemEditData.startTime"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="终止时间" prop="endTime">
          <el-date-picker
            v-model="itemEditData.endTime"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div class="dialogFooter">
        <el-button size="mini" @click="editDialogClose()">取消</el-button>
        <el-button
          type="primary"
          size="mini"
          @click="editDialogSubmit()"
        >保存</el-button>
      </div>
    </el-dialog>
    <!-- 历史记录窗口 -->
    <el-dialog title="历史记录" :visible.sync="showFormFlag" width="80%" center modal>
      <div>
        <MetaPageTable
          ref="historyTable"
          class="privateSecretManagement_table"
          table-title="历史记录列表"
          :is-auto-req="true"
          :req-url="historyReqUrl"
          :req-data="indexHistorySearch"
          req-method="post"
          :display-item="historyDisplayItem"
          :line-btn-group="historyLineBtnGroup"
          @lineBtnClick="modelInLineBtnClick"
        />
      </div>
    </el-dialog>
  </div>
</template>


<script>
import MetaPageTable from '../components/MetaPageTable'
import MetaSearchForm from '../components/MetaSearchForm'
import deepClone from '../utils/deepClone'
export default {
  name: 'privateSecretManagement',
  components: {
    MetaPageTable,
    MetaSearchForm
  },
  data () {
    return {
      historyLineBtnGroup: [
        {
          id: "historyDownload",
          title: "下载加密文件",
        },
      ],
      historyDisplayItem: [
        {
          label: '客户秘钥',
          prop: 'appSecret',
          width: "350",
        },
        {
          label: '机器标识',
          prop: 'hostKey'
        },
        {
          label: '生效时间',
          prop: 'startTime'
        },
        {
          label: '终止时间',
          prop: 'endTime'
        },
        {
          label: '生成时间',
          prop: 'createTime'
        }
      ],
      indexHistorySearch: {
        pid: "",
      },
      historyReqUrl: process.env.PROGOO_GATE_WATER + "private/getPrivateHistoryList",
      showFormFlag: false, // 隐藏/显示窗口
      apiCustomerInfoList: [],
      privateSecretDialogFlag: false,
      reqUrl: process.env.PROGOO_GATE_WATER + 'private/getPrivateList',
      itemEditData: {
        id: '',
        cid: '',
        hostKey:'',
        startTime:'',
        endTime:''
      },
      searchData: {},
      searchDataForTable: {},
      editRules: {},
      displayItem: [
        {
          label: '客户名称',
          prop: 'clientName'
        },
        {
          label: '生效时间',
          prop: 'startTime'
        },
        {
          label: '终止时间',
          prop: 'endTime'
        }
      ],
      btnGroup: [
        {
          id: 'add',
          title: '新建'
        }
      ],
      lineBtnGroup: [
        {
          id: 'edit',
          title: '编辑',
        },
        {
          id: 'delete',
          title: '删除'
        },
        {
          id:'secret',
          title: '生成'
        },
        {
          id:'history',
          title: '历史记录'
        }
      ],
    }
  },
  mounted() {
    // 初始化客户列表
    this.getApiCustomerInfoList();
  },
  methods: {
    modelInLineBtnClick(item) {
      if (item.button === "historyDownload") {
        this.axios({
          method: 'post',
          url: process.env.PROGOO_GATE_WATER + "private/historyDownload",
          data: {
            id: item.rows.id
          },
          responseType: 'blob'
        }).then(res => {
          if (res.data.code && res.data.code == 400) {
            this.$notify.error({
              title: '错误',
              message: res.data.message
            });
            return
          }
          const url = window.URL.createObjectURL(new Blob([res.data]))
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', 'ProgooLicense.lic')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        })
      }
    },
    getApiCustomerInfoList() {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "apiCustomerInfo/getAllList",
        method: "post",
        data: {},
      }).then((res) => {
        if (res.data.code === 200) {
          this.apiCustomerInfoList = res.data.result;
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    showClientName(e) {
      for (let i in this.apiCustomerInfoList) {
        if (e == this.apiCustomerInfoList[i].id) {
          this.itemEditData.clientName = this.apiCustomerInfoList[i].clientName;
        }
      }
    },
    tableBtnClick(item) {
      if (item.button === 'add') {
        this.itemEditData = {
          id: '',
          cid: '',
          hostKey:'',
          startTime:'',
          endTime:''
        }
        this.privateSecretDialogFlag = true
      }
    },
    tableInlineBtnClick(item) {
      if (item.button === 'edit') {
        this.itemEditData = deepClone(item.rows)
        this.privateSecretDialogFlag = true
      }else if (item.button === 'delete') {
        this.$confirm('确认删除此用户?', '用户删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "private/delete",
            method: "post",
            data: {
              id: item.rows.id
            }
          }).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.$nextTick(() => {
                this.$refs.privateSecretManagementTable.formDataInit(true)
              })
            }else {
              this.$notify.error({
                title: '错误',
                message: res.data.message
              });
            }
          })
        })
      }else if(item.button === 'secret'){
        this.$confirm('确认生成秘钥?', '生成秘钥', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "private/secret",
            method: "post",
            data: {
              id: item.rows.id
            }
          }).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.$nextTick(() => {
                this.$refs.privateSecretManagementTable.formDataInit(true)
              })
            }else {
              this.$notify.error({
                title: '错误',
                message: res.data.message
              });
            }
          })
        })
      }else if(item.button === 'history'){
        this.showFormFlag = true;
        this.indexHistorySearch.pid = item.rows.id;
        this.$nextTick(() => {
          this.$refs.historyTable.formDataInit(true);
        });
      }
    },
    tableSearch() {
      let param = {}
      for(let key in this.searchData) {
        if(key === 'dateBetween') {
          param.datestart = this.searchData[key] && this.searchData[key].length > 0 ? this.searchData[key][0] + ' 00:00:00' : ''
          param.dateend =  this.searchData[key] && this.searchData[key].length > 0 ? this.searchData[key][1] + ' 23:59:59' : ''
        }else {
          param[key] = this.searchData[key]
        }
      }
      this.searchDataForTable = param
      this.$nextTick(() => {
        this.$refs.privateSecretManagementTable.formDataInit(true)
      })

    },
    editDialogSubmit() {
      this.$refs['tPrivateSecretEdit_form'].validate((valid) => {
        if (valid) {
          let params = {}
          let url = process.env.PROGOO_GATE_WATER + "private/save"
          if(this.itemEditData.id !== '') {
            params.id = this.itemEditData.id
            url = process.env.PROGOO_GATE_WATER + "private/modify"
          }
          params.cid = this.itemEditData.cid
          params.hostKey = this.itemEditData.hostKey
          params.startTime = this.itemEditData.startTime
          params.endTime = this.itemEditData.endTime
          this.$fetch({
            url: url,
            method: "post",
            data: params
          }).then(res => {
            if (res.data.code === 200) {
              this.editDialogClose()
              this.$nextTick(() => {
                this.$refs.privateSecretManagementTable.formDataInit()
              })
            }else {
              this.$notify.error({
                title: '错误',
                message: res.data.message
              });
            }
          })
        } else {
          return false;
        }
      });
    },
    editDialogClose() {
      this.itemEditData = {
        id: '',
        cid: '',
        hostKey:'',
        startTime:'',
        endTime:''
      }
      this.privateSecretDialogFlag = false
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.privateSecretManagement{
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 15px;
  overflow-y: scroll;
  .privateSecretManagement_table {
    width: 100%;
    overflow-y: unset;
  }
  .dataDetailsForm_item {
    line-height: normal;
    padding: 8px 0;
  }
  .privateSecretManagement_searchFrom {
    width: 100%;
  }
  .privateSecretManagement_searchFromItem {
    float: left;
  }
  .dialogFooter {
    display: flex;
    justify-content: center;
    margin-top: 0.5rem;
  }
}
</style>
